'use strict'
const path = require('path');

module.exports = function(app, currentPath, middlewares){
  /**
   * 中间件加载操作
   * @param {app} 读取到的中间件配置
   * @param {middlewares} 读取到的中间件配置
   */
  var fn;
  let length = middlewares.length;
  for(let i = 0; i <= length-1; i++){
    if(typeof(middlewares[i]) == 'string'){  //检查是否是简单的中间件配置
      //简单的中间件配置，包名称或者本地路径
      fn = require(path.join(currentPath,middlewares[i]));
      //简单的中间件配置  默认是启用不加载
      app.use(fn);
    }else{
      if(middlewares[i].path && middlewares[i].path.length > 0){
        //按本地路径加载中间件
        fn = require(path.join(currentPath,middlewares[i].path));
      }else if (middlewares[i].package && middlewares[i].package.length > 0) {
        //检查是否是包下面的函数
        if(middlewares[i].package.indexOf('.') >= 0){
          let pkgArr = middlewares[i].package.split(".");
          let pkg = require(pkgArr[0]);
          fn = pkg.pkgArr[1];
        }else{
          //按包名加载中间件
          fn = require(path.join(currentPath,middlewares[i].package));
        }
      }

      var fns = fn;
      //成功加载中间件  加载过程中包已执行，中间件为执行后返回的异步函数
      if(middlewares[i].options.length >= 1){
        fns = fn.apply(null,middlewares[i].options);
        // console.log(fns);
      }

      //检查中间件类型 启用、加载
      if(middlewares[i].enable == true || middlewares[i].enable == "true"){
        app.use(fns);
      }
      if(middlewares[i].hold == true || middlewares[i].hold == "true"){
        let funName = fns.getName()
        if(funName){
          app.holdList.middlewares[funName] = fns;
        }
      }
    }
  }
}
